package com.leesche.zcsp.node.pay.cmbc.service.impl;

import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.pay.cmbc.service.CmbcPayService;
import com.leesche.zcsp.node.pay.cmbc.util.ConfigUtil;
import com.leesche.zcsp.node.pay.cmbc.util.SSLClient;
import com.leesche.zcsp.node.pay.cmbc.util.SignUtil;
import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.utils.AlipayConfig;
import com.leesche.zcsp.node.utils.NetConfig;
import com.leesche.zcsp.node.utils.PayConfig;
import com.leesche.zcsp.node.utils.TenpayUtil;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.PubDevice;
import com.leesche.zcsp.node.web.model.PubDevicePayDetail;
import com.leesche.zcsp.node.web.model.ServOrder;
import com.leesche.zcsp.node.web.service.PubDevicePayDetailService;
import com.leesche.zcsp.node.web.service.PubDeviceService;
import com.leesche.zcsp.node.web.service.ServOrderService;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author reid
 * @Created 16/11/16
 */
@Service
@SuppressWarnings("all")
public class CmbcPayServiceImpl implements CmbcPayService {

    public static final Logger LOGGER = Logger.getLogger(CmbcPayServiceImpl.class);

    private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    private static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
    private static final SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final String INSERT_PAYDETAIL = "insert into t_pub_device_pay_detail (DeviceID, PayType, money, "
            + "Coin, Cash, Quantity, ReceiveTime, UploadTime, userid, CreateTime,recordid) " + "values (#deviceId," +
            "#payType,#money,#coin,#cash,#quantity,#receiveTime,#uploadTime,#userId,#createTime,#recordId);";


    @Autowired
    private NetService netService;
    @Autowired
    private ServOrderService orderService;
    @Autowired
    private PubDeviceService deviceService;
    @Autowired
    public PubDevicePayDetailService payDetailService;

    /**
     * @param order     订单信息
     * @param openId    微信公众号openid
     * @param userAgent
     * @return
     * @throws Exception
     * @Description: 预支付处理接口, 生成支付所需参数信息
     */
    @Override
    public Message<String> prePay(ServOrder order, String openId, String userAgent) {
        Date now = new Date();

        try {
            DefaultHttpClient httpClient = new SSLClient();
            HttpPost postMethod = new HttpPost(ConfigUtil.getProperty("trans_url"));
            List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
            nvps.add(new BasicNameValuePair("requestNo", sdf1.format(now)));
            nvps.add(new BasicNameValuePair("version", "V1.0"));
            nvps.add(new BasicNameValuePair("transId", "10"));
            nvps.add(new BasicNameValuePair("merNo", ConfigUtil.getProperty("merchant_no")));
            nvps.add(new BasicNameValuePair("orderDate", sdf2.format(now)));
            nvps.add(new BasicNameValuePair("orderNo", order.getOutTradeNo()));
            nvps.add(new BasicNameValuePair("transAmt", String.valueOf(order.getCashFee())));
            nvps.add(new BasicNameValuePair("commodityName", "娃娃机游戏币"));
            nvps.add(new BasicNameValuePair("openid", openId));

            if (userAgent.equalsIgnoreCase("wechat")) {
                //微信支付
                nvps.add(new BasicNameValuePair("productId", "0105"));
                nvps.add(new BasicNameValuePair("subMerNo", PayConfig.CMBC_SUBMERNO));
                nvps.add(new BasicNameValuePair("subMerName", PayConfig.CMBC_SUBMERNAME));
                nvps.add(new BasicNameValuePair("returnUrl", PayConfig.CMBC_NOTIFY_URL));
                nvps.add(new BasicNameValuePair("notifyUrl", PayConfig.CMBC_NOTIFY_URL));
            } else if (userAgent.equalsIgnoreCase("alipay")) {
                //支付宝支付
                nvps.add(new BasicNameValuePair("productId", "0109"));
                nvps.add(new BasicNameValuePair("storeId", AlipayConfig.partner));
                nvps.add(new BasicNameValuePair("terminalId", AlipayConfig.partner));
                nvps.add(new BasicNameValuePair("returnUrl", PayConfig.CMBC_NOTIFY_URL));
                nvps.add(new BasicNameValuePair("notifyUrl", PayConfig.CMBC_NOTIFY_URL));
            }
            nvps.add(new BasicNameValuePair("signature", SignUtil.signData(nvps)));

            postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

            long t1 = System.currentTimeMillis();
            HttpResponse resp = httpClient.execute(postMethod);
            long t2 = System.currentTimeMillis();
            LOGGER.info("民生预支付耗时: " + (t2 - t1));

            String ret = EntityUtils.toString(resp.getEntity(), "UTF-8");
            LOGGER.info("民生银行预支付返回结果：" + ret);

            int statusCode = resp.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                boolean signFlag = SignUtil.verferSignData(ret);
                if (!signFlag) {
                    LOGGER.info("验签失败!");
                    return Message.error("验签失败", new Object[0]);
                }

                HashMap<String, String> map = parseStringToMap(ret);
                if (map.get("respCode").equalsIgnoreCase("P000")) {
                    if (userAgent.equalsIgnoreCase("wechat")) {
                        String payInfo = map.get("payInfo");
                        return Message.success(payInfo, new Object[0]);
                    } else {
                        return Message.success("交易成功", new Object[0]);
                    }
                } else {
                    return Message.error(map.get("respDesc"), new Object[0]);
                }
            }
//            LOGGER.info("返回错误码:" + statusCode);
            return Message.error("交易失败", new Object[0]);
        } catch (ClientProtocolException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return Message.error("交易失败", new Object[0]);
    }

    /**
     * @param transAmt      金额
     * @param custtomerName 收款方客户名称
     * @param acctNo        收款方银行账号
     * @Description: 代付/转账
     */
    @Override
    public Map<String, String> transfer(Long transAmt, String custtomerName, String acctNo) {
        Date now = new Date();
        Map<String, String> map = new HashMap<String, String>();

        try {
            DefaultHttpClient httpClient = new SSLClient();
            HttpPost postMethod = new HttpPost(ConfigUtil.getProperty("trans_url"));
            List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
            nvps.add(new BasicNameValuePair("requestNo", sdf1.format(now)));
            nvps.add(new BasicNameValuePair("version", "V1.0"));
            nvps.add(new BasicNameValuePair("productId", "0201"));// 0201-非垫支/普通代付,0203-垫支/额度代付
            nvps.add(new BasicNameValuePair("transId", "07"));
            nvps.add(new BasicNameValuePair("merNo", ConfigUtil.getProperty("merchant_no")));
            nvps.add(new BasicNameValuePair("orderDate", sdf2.format(now)));
            nvps.add(new BasicNameValuePair("orderNo", TenpayUtil.getOrderNo()));
            nvps.add(new BasicNameValuePair("notifyUrl", PayConfig.CMBC_NOTIFY_URL));
            nvps.add(new BasicNameValuePair("transAmt", String.valueOf(transAmt)));//金额,单位分
            nvps.add(new BasicNameValuePair("isCompay", "0"));// 0-对私,1-对公
//        nvps.add(new BasicNameValuePair("phoneNo", "13312345678"));
            nvps.add(new BasicNameValuePair("customerName", custtomerName));
//        nvps.add(new BasicNameValuePair("cerdType", "01"));//证件类型
//        nvps.add(new BasicNameValuePair("cerdId", "110000197609260652"));//证件号
//        nvps.add(new BasicNameValuePair("accBankNo", "105100000025"));
//        nvps.add(new BasicNameValuePair("accBankName", "建设银行"));
            nvps.add(new BasicNameValuePair("acctNo", acctNo));//银行卡号 "6227003322710172543"
//        nvps.add(new BasicNameValuePair("note", "test"));
            nvps.add(new BasicNameValuePair("signature", SignUtil.signData(nvps)));

            postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            HttpResponse resp = httpClient.execute(postMethod);
            String ret = EntityUtils.toString(resp.getEntity(), "UTF-8");
            LOGGER.info("minsheng transfer return: " + ret);
            HashMap retMap = parseStringToMap(ret);

            int statusCode = resp.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                boolean signFlag = SignUtil.verferSignData(ret);
                if (!signFlag) {
                    LOGGER.warn("验签失败");
                    map.put("result", "fail");
                } else if (retMap.get("respCode").equals("0000")) {
                    map.put("result", "success");
                } else {
                    map.put("result", "fail");
                }
                map.put("orderNo", retMap.get("orderNo").toString());
                map.put("respDesc", retMap.get("respDesc").toString());
            }
            return map;
        } catch (ClientProtocolException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        map.put("result", "fail");
        return map;
    }

    /**
     * @param requestNo     交易请求流水号
     * @param origOrderDate 原商品订单的日期yyyyMMdd
     * @param origOrderNo   原交易商户订单号
     * @param transAmt      退款金额
     * @param refundReson   退款原因
     * @return
     * @throws Exception
     * @Description: 申请退款
     */
    @Override
    public Message<String> refund(String requestNo, String origOrderDate, String origOrderNo, long transAmt, String refundReson) {
        Date now = new Date();

        try {
            DefaultHttpClient httpClient = new SSLClient();
            HttpPost postMethod = new HttpPost(ConfigUtil.getProperty("trans_url"));
            List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
            nvps.add(new BasicNameValuePair("requestNo", sdf1.format(now)));
            nvps.add(new BasicNameValuePair("version", "V1.0"));
            nvps.add(new BasicNameValuePair("transId", "02"));
            nvps.add(new BasicNameValuePair("merNo", ConfigUtil.getProperty("merchant_no")));
            nvps.add(new BasicNameValuePair("orderDate", sdf2.format(now)));
            nvps.add(new BasicNameValuePair("orderNo", TenpayUtil.getOrderNo()));
            nvps.add(new BasicNameValuePair("origOrderDate", origOrderDate));//原交易日期
            nvps.add(new BasicNameValuePair("origOrderNo", origOrderNo));//原交易单号
            nvps.add(new BasicNameValuePair("returnUrl", PayConfig.CMBC_NOTIFY_URL));
            nvps.add(new BasicNameValuePair("notifyUrl", PayConfig.CMBC_NOTIFY_URL));
            nvps.add(new BasicNameValuePair("transAmt", String.valueOf(transAmt)));//金额,单位分
            nvps.add(new BasicNameValuePair("refundReson", refundReson));//退款原因
            nvps.add(new BasicNameValuePair("signature", SignUtil.signData(nvps)));

            postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            HttpResponse resp = httpClient.execute(postMethod);
            String str = EntityUtils.toString(resp.getEntity(), "UTF-8");
            System.out.println("resp.getEntity=" + str);
            int statusCode = resp.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                boolean signFlag = SignUtil.verferSignData(str);
                if (!signFlag) {
                    System.out.println("验签失败");
                    return Message.error("验签失败", new Object[0]);
                }

                HashMap map = parseStringToMap(str);
                if (map.get("respCode").equals("0000")) {
                    return Message.success(map.get("respDesc"), new Object[0]);
                }
                return Message.error(map.get("respDesc"), new Object[0]);
            }
        } catch (ClientProtocolException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return Message.error("退款失败", new Object[0]);
    }

    /**
     * @param requestNo 交易请求流水号
     * @param orderDate 商品订单日期yyyyMMdd
     * @param orderNo   商户订单号
     * @return
     * @throws Exception
     * @Description: 查询交易订单状态
     */
    @Override
    public Message<String> queryOrderState(String orderDate, String orderNo) {
        Date now = new Date();

        try {
            DefaultHttpClient httpClient = new SSLClient();
            HttpPost postMethod = new HttpPost(ConfigUtil.getProperty("trans_url"));
            List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
            nvps.add(new BasicNameValuePair("requestNo", sdf1.format(now)));
            nvps.add(new BasicNameValuePair("version", "V1.0"));
            nvps.add(new BasicNameValuePair("transId", "04"));
            nvps.add(new BasicNameValuePair("merNo", ConfigUtil.getProperty("merchant_no")));
            nvps.add(new BasicNameValuePair("orderDate", orderDate));
            nvps.add(new BasicNameValuePair("orderNo", orderNo));
            nvps.add(new BasicNameValuePair("signature", SignUtil.signData(nvps)));

            postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            HttpResponse resp = httpClient.execute(postMethod);
            String str = EntityUtils.toString(resp.getEntity(), "UTF-8");
            System.out.println("resp.getEntity=" + str);
            int statusCode = resp.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                boolean signFlag = SignUtil.verferSignData(str);
                if (!signFlag) {
                    System.out.println("验签失败");
                    return Message.error("验签失败", new Object[0]);
                }

                HashMap map = parseStringToMap(str);
                if (map.get("respCode").equals("0000")) {
                    //respCode不等于0000时当未知状态处理,继续调用查询接口;respCode等于0000时以oridRespCode返回码为准
                    return Message.success(map.get("origRespDesc"), new Object[0]);
                }
                return Message.error(map.get("respDesc"), new Object[0]);
            }
        } catch (ClientProtocolException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return Message.error("查询失败", new Object[0]);
    }

    /**
     * @param origOrderNo 原交易商户订单号
     * @param transAmt    交易金额,单位为分,撤销金额需等于原订单金额
     * @return
     * @throws Exception
     * @Description: 撤销当天交易, 其他时间交易撤销始终报失败
     */
    @Override
    public Message<String> undoOder(String orderNo, long transAmt) {
        Date now = new Date();

        try {
            DefaultHttpClient httpClient = new SSLClient();
            HttpPost postMethod = new HttpPost(ConfigUtil.getProperty("trans_url"));
            List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
            nvps.add(new BasicNameValuePair("requestNo", sdf1.format(now)));
            nvps.add(new BasicNameValuePair("version", "V1.0"));
            nvps.add(new BasicNameValuePair("transId", "03"));
            nvps.add(new BasicNameValuePair("merNo", ConfigUtil.getProperty("merchant_no")));
            nvps.add(new BasicNameValuePair("orderDate", sdf2.format(now)));
            nvps.add(new BasicNameValuePair("orderNo", TenpayUtil.getOrderNo()));
            nvps.add(new BasicNameValuePair("origOrderNo", orderNo));
            nvps.add(new BasicNameValuePair("returnUrl", PayConfig.CMBC_NOTIFY_URL));
            nvps.add(new BasicNameValuePair("notifyUrl", PayConfig.CMBC_NOTIFY_URL));
            nvps.add(new BasicNameValuePair("transAmt", String.valueOf(transAmt)));//金额,单位分
            nvps.add(new BasicNameValuePair("signature", SignUtil.signData(nvps)));

            postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            HttpResponse resp = httpClient.execute(postMethod);
            String str = EntityUtils.toString(resp.getEntity(), "UTF-8");
            System.out.println("resp.getEntity=" + str);
            int statusCode = resp.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                boolean signFlag = SignUtil.verferSignData(str);
                if (!signFlag) {
                    System.out.println("验签失败");
                    return Message.error("验签失败", new Object[0]);
                }

                HashMap map = parseStringToMap(str);
                if (map.get("respCode").equals("0000")) {
                    return Message.success(map.get("respDesc"), new Object[0]);
                }
                return Message.error(map.get("respDesc"), new Object[0]);
            }
        } catch (ClientProtocolException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return Message.error("查询失败", new Object[0]);
    }

    /**
     * 查询账户余额
     * @return
     */
    @Override
    public Message<String> queryBalance() {
        Date now = new Date();

        try {
            DefaultHttpClient httpClient = new SSLClient();
            HttpPost postMethod = new HttpPost(ConfigUtil.getProperty("trans_url"));
            List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
            nvps.add(new BasicNameValuePair("requestNo", sdf1.format(now)));
            nvps.add(new BasicNameValuePair("version", "V1.0"));
            nvps.add(new BasicNameValuePair("transId", "09"));
            nvps.add(new BasicNameValuePair("merNo", ConfigUtil.getProperty("merchant_no")));
            nvps.add(new BasicNameValuePair("signature", SignUtil.signData(nvps)));

            postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            HttpResponse resp = httpClient.execute(postMethod);
            String str = EntityUtils.toString(resp.getEntity(), "UTF-8");
            System.out.println("resp.getEntity=" + str);
            int statusCode = resp.getStatusLine().getStatusCode();
            if (200 == statusCode) {
                boolean signFlag = SignUtil.verferSignData(str);
                if (!signFlag) {
                    System.out.println("验签失败");
                    return Message.error("验签失败", new Object[0]);
                }

                HashMap map = parseStringToMap(str);
                if (map.get("respCode").equals("0000")) {
                    return Message.success(map.get("respDesc"), new Object[0]);
                }
                return Message.error(map.get("respDesc"), new Object[0]);
            }
        } catch (ClientProtocolException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }


        return null;
    }

    /**
     * 民生支付回调通知
     * @param paramMap
     * @return
     */
    @Override
    public String notify(Map paramMap) {
        Map<String, String> map = getNotifyParams(paramMap);
        String orderNo = map.get("orderNo").toString();
        String productId = map.get("productId").toString();
        String respCode = map.get("respCode").toString();
        String respDesc = map.get("respDesc").toString();

        Date now = new Date();

        if (productId.equals("0105") || productId.equals("0109")) {
            int payType = 0;
            if (productId.equals("0105")) {
                payType = NetConfig.PAYTYPE_WECHAT;
            } else if (productId.equals("0109")) {
                payType = NetConfig.PAYTYPE_ALIPAY;
            }

            try {
                //查询订单
                ServOrder servOrder = orderService.findServOrderByOrderNo(orderNo);
                //查询设备
                PubDevice pubDevice = deviceService.selectByPrimaryKey(servOrder.getDeviceid());

                if (servOrder != null && servOrder.getTradeState() != 1 && pubDevice != null) {
                    if (respCode.equals("0000")) {
                        servOrder.setTradeState(Constants.TRADE_STATE_SUCCESS);
                        servOrder.setTradeStateDesc("民生支付成功");
                        servOrder.setTimeEnd(now);
                        orderService.updateByPrimaryKey(servOrder);

                        //支付成功才调用出币流程
                        netService.sendClientBuy(pubDevice, servOrder.getCashFee() / 100, servOrder.getCoin(), payType, servOrder);

                        insertPayDetail(pubDevice, servOrder, payType);
                    } else {
                        servOrder.setTimeEnd(now);
                        servOrder.setTradeState(Constants.TRADE_STATE_PAYERROR);
                        servOrder.setTradeStateDesc(respDesc);
                        orderService.updateByPrimaryKey(servOrder);
                    }
                }
                LOGGER.info("minsheng pay notify success......");
                return "SUCCESS";
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
                return "FAIL";
            }
        }
        return "SUCCESS";
    }

    /**
     * 插入流水表
     * @param pubDevice
     * @param servOrder
     * @param payType
     */
    private void insertPayDetail(PubDevice pubDevice, ServOrder servOrder, int payType) {
        Date now = new Date();
        PubDevicePayDetail detail = new PubDevicePayDetail();
        detail.setDeviceid(pubDevice.getDeviceid());
        detail.setPlaceid(pubDevice.getPlaceid());
        detail.setUserid(pubDevice.getAdminid());
        detail.setPaytype(payType);
        detail.setCoin(servOrder.getCashFee());
        detail.setCash(0);
        detail.setMoney(0);
        detail.setQuantity(0);
        detail.setCreatetime(now);
        detail.setReceivetime(now);
        detail.setUploadtime(now);
        detail.setRecordid(servOrder.getCreatetime().getTime());

        try {
            payDetailService.insert(detail);
        } catch (Exception e) {
            LOGGER.error("写入交易明细数据失败,保存SQL到临时文件! ", e);

            //写数据库失败,生成SQL 保存到临时文件
            String sql = INSERT_PAYDETAIL.replace("#deviceId", String.valueOf(detail.getDeviceid()))
                    .replace("#payType", String.valueOf(detail.getPaytype()))
                    .replace("#money", String.valueOf(detail.getMoney()))
                    .replace("#coin", String.valueOf(detail.getCoin()))
                    .replace("#cash", String.valueOf(detail.getCash()))
                    .replace("#quantity", String.valueOf(detail.getQuantity()))
                    .replace("#receiveTime", "'" + sdf3.format(detail.getReceivetime()) + "'")
                    .replace("#uploadTime", "'" + sdf3.format(detail.getUploadtime()) + "'")
                    .replace("#userId", String.valueOf(detail.getUserid()))
                    .replace("#createTime", "'" + sdf3.format(detail.getCreatetime()) + "'")
                    .replace("#recordId", String.valueOf(detail.getRecordid()));

            LOGGER.info("INSERT_PAYDETAIL: " + sql);

            File file = new File("/data/backup/pay_detail.txt");
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }

                FileOutputStream os = new FileOutputStream(file, true); //如果追加方式用true
                os.write((sql + "\n\n").getBytes("UTF-8"));
                os.close();
            } catch (FileNotFoundException e1) {
                LOGGER.error(e1.getMessage(), e1);
            } catch (IOException e2) {
                LOGGER.error(e2.getMessage(), e2);
            }
        }
    }

    /**
     * 把民生银行返回的字符串转换成Map
     * @param str
     * @return resp.getEntity=acctNo=6227003322710172543&customerName=林永福&isCompay=0&merNo=850440058121106
     * &notifyUrl=http://youyicloud.net/node/pay/minsheng/callback&orderDate=20161117
     * &orderNo=4e556800b0664de8b2804e9b91cbe0e6&productId=0201&requestNo=20161117155225838
     * &respCode=0042&respDesc=余额不足&transAmt=1&transId=07&version=V1.0
     * &signature=HmR0iDhtb3ckSvnmPeqREntw5X07W9jY1yFDlf6UIQWSVk0DVmt01XF3nUPqut9MVcFngcYC3vWhB4qC+L54DRhpAhriWvs7jiva1XmMTujJhO4d9rsjApjVbU3KUoo3aeOO9nrkz8lmUCguxwspF3WiNrWhY4PZYbEb4iN2GQuYaCUcU4sRtJJ2Rek4Udl71h7HHx3z5qSXSuPd2fLmrgyj47h0xRPSW2a8iWVgoLK4LCoZsonPClJte8uMLvGty1DuUcBsnHtNQyygLpwHF0vrOs3RYzdU8nfbj95/s5BBiMkFOkMfG7jyC96xCufystmOu2LyKagIZrhdpz+7fg==
     */
    private HashMap<String, String> parseStringToMap(String str) {
        HashMap<String, String> map = new HashMap<String, String>();
        String[] arr = str.split("&");
        for (int i = 0; i < arr.length; i++) {
            String tmp[] = arr[i].split("=", 2);
            map.put(tmp[0], tmp[1]);
        }
        return map;
    }


    private Map<String, String> getNotifyParams(Map requestParams) {
        Map<String, String> params = new HashMap<String, String>();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
            LOGGER.info("minsheng notify params:" + name + "=" + valueStr);
        }
        return params;
    }

}
